const { exec } = require('child_process');
const axios = require('axios');
const zlib = require('zlib');
const { promises } = require('dns');

const excludeFromDiff = (path) => `:(exclude)${path}`;
const filesToExclude = [
  "*.zip",
  "*.7z",
  "*.tar.gz",
  "*.zip",
  "*.rar",
  "*.iso",
  "*.exe",
  "*.dmg",
  "unpackage",
  "dist",
  "nuxt-dist",
  "node_modules"
].map(excludeFromDiff);
const executeCommand = (command) => {
  return new Promise((resolve, reject) => {
    exec(command, (error, stdout, stderr) => {
      if (error) {
        reject(error);
      } else {
        resolve(stdout.split("\n").filter(Boolean));
      }
    });
  });
}
module.exports = {
  getOrigin: () => {
    return new Promise((resolve, reject) => {
      exec(
        'git remote get-url origin',
        (error, stdout, stderr) => {
          if (error) {
            reject('error');
          } else {
            resolve(stdout);
          }
        }
      );
    });
  },

  getParse: () => {
    return new Promise((resolve, reject) => {
      exec(
        'git rev-parse --show-toplevel',
        (error, stdout, stderr) => {

          if (error) {
            reject('当前目录必须是Git存储库！');
          } else {
            resolve(stdout);
          }
        }
      );
    });
  },

  compressData: (data) => {
    return new Promise((resolve, reject) => {
      zlib.deflate(data, (error, buffer) => {
        if (error) {
          reject(error);
        } else {
          resolve(buffer);
        }
      });
    });
  },
  getDiff: () => {
    return new Promise((resolve, reject) => {
      exec(
        `git diff --cached --diff-algorithm=minimal ${filesToExclude.join(" ")}`,
        (error, stdout, stderr) => {

          if (stdout) {
            resolve(stdout);
          } else {
            reject(error);

          }

        }
      );
    });
  },

  getAi: (t) => {
    return new Promise((resolve, reject) => {
      const postData = {
        t: t
      };
      // JSON.stringify(postData)
      axios.post('https://fc-mp-7d13aaae-6ab7-4da9-b4f0-115c02a1486f.next.bspapp.com/http/route/client/pub.index.getdiff', JSON.stringify(postData), {
        headers: {
          'Content-Encoding': 'gzip', // 设置请求头，指定数据使用gzip压缩
          'Content-Type': 'application/json' // 设置请求头，指定数据类型为JSON
        }
      })
        .then((response) => {

          if (response.data.code == 0) {
            let processedString = response.data.data.reply.replace(/\n/g, '').replace(/\+/g, '');

            resolve(processedString);

          } else {
            reject(response.data.msg)
          }
        })
        .catch((error) => {

          reject(error)
        });
    });

  },
  gitCommit: (t) => {
    return new Promise((resolve, reject) => {
      exec(`git commit -m "${t}"`, (error, stdout, stderr) => {
        if (error) {
          reject(error);
        } else {
          resolve(stdout);
        }
      });
    });

  },
  gitPush: () => {
    return new Promise((resolve, reject) => {
      exec('git push', (error, stdout, stderr) => {
        if (error) {
          reject(error);
        } else {
          resolve(stdout);
        }
      });
    });

  },
  getPull: () => {
    return new Promise((resolve, reject) => {
      exec('git pull', (error, stdout, stderr) => {
        if (error) {
          reject(error);
        } else {
          resolve(stdout);
        }
      });
    })
  },
  getReset: () => {
    return new Promise((resolve, reject) => {
      exec('git reset', (error, stdout, stderr) => {
        if (error) {
          reject(error);
        } else {
          resolve(stdout);
        }
      });
    })
  },
  //这样就成功撤销了commit，如果想要连着add也撤销的话，--soft改为--hard（删除工作空间的改动代码）。
  submitWdrl: () => {
    return new Promise((resolve, reject) => {
      exec('git reset --soft HEAD^', (error, stdout, stderr) => {
        if (error) {
          reject(error);
        } else {
          resolve(stdout);
        }
      });
    })
  },

  getNameonlys: () => {
    return new Promise((resolve, reject) => {

      const all = [
        executeCommand(`git diff --name-only  ${filesToExclude.join(" ")}`),
        executeCommand(`git ls-files --others --exclude-standard  ${filesToExclude.join(" ")}`)
      ]
      Promise.all(all).then((res) => {

        if (res.flat().length == 0) {
          reject('reject')
        } else {
          resolve(res.flat());
        }
      }).catch((err) => {
        reject('reject')
      });
    })
  },
  //git diff --name-only
  gitAdd: (url) => {
    //

    return new Promise((resolve, reject) => {
      // git add --update 只添加被修改或被删除的文件，不添加新创建的文件。
      // git add . 添加当前目录下的所有文件（包括新创建的文件）和子目录中的已修改或已删除的文件
      exec(`git add ${url}`, (error, stdout, stderr) => {

        if (error) {
          reject(error);
        } else {
          resolve(stdout);
        }
      });
    });
  },
}